#################################################################################

source('lisa_perm.R')
source('pm.R')
source('plot_classInt.R')

#---------------------------Total Energy Consumption----------------------------#
#energia<-read.csv('data/consumo_energia.csv',header=TRUE,sep=';')

#totec<-energia[,c(3:4,6:16)];vnames<-names(totec[,4:13])
#totec<-reshape(totec,v.names=vnames,timevar='Ano',idvar='Divipola',direction='wide')

energia<-read.csv('data/consumo_energia.csv',header=TRUE,sep=';')

totec<-energia[,-3];vnames<-names(totec[,3:12])
totec<-reshape(totec,v.names=vnames,timevar='year',idvar='Divipola',direction='wide')

#################################################################################
#--------------------Per Capita Total Energy Consumption------------------------#

pob<-read.csv('data/poblacion.csv',header=TRUE,sep=';')


# Sort the data by the municipal numeric identifier 'divipola'
totec<-totec[ order(totec$Divipola),]
pob<-pob[ order(pob$Divipola),]
#identical(pob$Divipola,totec$Divipola)

year<-c(1996:1997,1999:2012)

pc<-totec

for(i in seq_along(vnames)){
vnames1<-paste(vnames[i],year,sep='.')
vnames2<-paste('tot',year,sep='')

# Calculate the per capita energy consumption

pc[,vnames1]<-totec[,vnames1]/pob[,vnames2]

}

pc[is.na(pc)==1]<-0
for(i in 1:ncol(pc)){
    pc[pc[,i]=='Inf',i]<-0    
}

# Drop unconnected regions
totec<-subset(totec, !(totec$Divipola %in% c(5475,5873)))
pc<-subset(pc, !(pc$Divipola %in% c(5475,5873)))

#################################################################################
#-----------------------------Antioquia's Shape---------------------------------#

library(spdep)
library(maptools)

# Load Antioquia's shape file
ant<-readShapePoly('data/antioquia.shp')


# Set rownames, namely, change feature identifier in spatial object
row.names(ant)<-as.character(ant$ID_ESPAC_2)

# Check rownames, to confirm that the preceeding had the desired effect
#identical(row.names(ant),sapply(ant@polygons, function(x) slot(x,"ID")))

# Re-order
ant<-ant[order(row.names(ant)),]

# Indeed, the reordering worked
#row.names(ant)
ant<-subset(ant, !(ant$ID_ESPAC_2 %in% c(5475,5873)))

#################################################################################
#-----------------------------Travel Times Matrix-------------------------------#

odh<-read.table('data/od-matrix-h.csv',sep=';')

#identical(pc$Divipola,totec$Divipola,as.numeric(ant$ID_ESPAC_2),as.numeric(rownames(odh)))

#################################################################################
#------------------------------Market Potential---------------------------------#

W<-as.matrix(odh);colnames(W)<-rownames(W)

#for(i in seq_along(vnames1)){
#    totec[,vnames1[i]]<-pm(totec,W,mass.var=vnames1[i])$pmR
#}


#################################################################################

library(shiny)

# Define server logic for random distribution application
shinyServer(function(input, output, session) {
    data <- reactive({
        data<-get(input$data)
        x <- rowSums(cbind(0,data[,paste(input$var,input$year,sep='.')]))
        
        if(input$log==TRUE){
            x[x>0] <- log(x[x>0])
        }
        
        if(input$std=='mean'){
            x <- x/mean(x)
        } else if(input$std=='median'){
            x <- x/median(x)
        }
        
        x
    })
    
    output$plot1 <- renderPlot({        
                    
        W<-as.matrix(odh);colnames(W)<-rownames(W)
        W<-(W>=0 & W<input$hdist)
        W<-W/rowSums(W)
        lw<-mat2listw(W,row.names=rownames(W),style='W')
        
        lmoran<-lisa.perm(data(),lw,perm=input$perm)
        plot.lisaPerm(lmoran,ant,signif=input$signif,legend.title=paste('Consumo de energia',input$year,sep=', '))
    })
    output$plot2 <- renderPlot({        
                        
        plot.classInt(data(),ant,main='Coropleth Map',
                      legend.title=paste('Consumo de energia',input$year,sep=', '),
                      style=input$style,n=input$int)
    })
    
  })
    
